﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
using System.Threading;
using System.ComponentModel;

public partial class PasswordRecoveryPage : PageBase
{
    static bool mailSent = false;

    protected void Page_Load( object sender, EventArgs e )
    {
        if ( !Page.IsPostBack )
        {
        }
    }

    protected void PasswordRecovery1_SendingMail( object sender, MailMessageEventArgs e )
    {
        SmtpClient SmtpMail = new SmtpClient( Config.MailServerSmtp );
        try
        {
            SmtpMail.Send( e.Message );
        }
        catch ( SmtpFailedRecipientsException ex )
        {
            for ( int i = 0; i < ex.InnerExceptions.Length; i++ )
            {
                SmtpStatusCode status = ex.InnerExceptions[ i ].StatusCode;
                if ( status == SmtpStatusCode.MailboxBusy
                     || status == SmtpStatusCode.MailboxUnavailable )
                {
                    PasswordRecovery1.SuccessText += "<br>Delivery failed - retrying in 5 seconds.";
                    System.Threading.Thread.Sleep( 5000 );
                    SmtpMail.Send( e.Message );
                }
                else
                {
                    PasswordRecovery1.SuccessText += "<br>Failed to deliver message : " + ex.FailedRecipient[ i ];
                }
            }
        }
        catch ( SmtpException ex )
        {
            PasswordRecovery1.SuccessText += "Erreur : ";
            PasswordRecovery1.SuccessText += ex.Message;
        }
        catch ( HttpException ex )
        {
            PasswordRecovery1.SuccessText += "Erreur : <br>";
            PasswordRecovery1.SuccessText += ex.Message;
        }
        catch ( Exception ex )
        {
            PasswordRecovery1.SuccessText += "Erreur : <br>";
            PasswordRecovery1.SuccessText += ex.Message;
        }
    }

    public static void SendCompletedCallback( object sender, AsyncCompletedEventArgs e )
    {
        // Get the unique identifier for this asynchronous operation.
        String token = ( string )e.UserState;

        if ( e.Cancelled )
        {
            Console.WriteLine( "[{0}] Send canceled.", token );
        }
        if ( e.Error != null )
        {
            Console.WriteLine( "[{0}] {1}", token, e.Error.ToString() );
        }
        else
        {
            Console.WriteLine( "Message sent." );
        }
        mailSent = true;
    }
}
